#include "hal.h"
#include "sensors.h"


volatile union_sensor sensores;
volatile uint32_t sensor_pressao;

/**********************************************************************************
 * Descrição:
 *
 * Paramêtro(s):
 *					-
 * Retorno:
 *					-
 **********************************************************************************/
void sensors_init (void)
{
	extern PINSEL_CFG_Type PinCfg;
	
    GPIO_SetDir(2,SENSORES,0);
    sensores.u32=0;
    /*Inicializa o AD */
        PinCfg.Funcnum	 = 1;
	PinCfg.OpenDrain = 0;
	PinCfg.Pinmode	 = 0;
	PinCfg.Pinnum	 = 25;
	PinCfg.Portnum	 = 0;
	PINSEL_ConfigPin( &PinCfg );
	ADC_Init( LPC_ADC, 200000 );
	ADC_ChannelCmd( LPC_ADC, ADC_CHANNEL_2, ENABLE );
	ADC_BurstCmd( LPC_ADC, ENABLE );

	sensor_pressao	=	0;	//inicializa o valor de pressao com zero

}

/**********************************************************************************
 * Descrição:
 *
 * Paramêtro(s):
 *					-
 * Retorno:
 *					-
 **********************************************************************************/
uint16_t sensors_read (uint8_t xSensor)
{
	if (xSensor != SENSORPRESSAO) 
	{
		return GPIO_ReadValue(PORT_SENSORES);
	}
	else
	{
		return ADC_ChannelGetData( LPC_ADC, ADC_CHANNEL_2 );
	}
}

/**********************************************************************************
 * Descrição:
 *
 * Paramêtro(s):
 *					-
 * Retorno:
 *					-
 **********************************************************************************/
void sensors_isr_read (void)
{
	#define SAMPLE		200
	static uint32_t	valormedio	=	0;
	static uint32_t	media	=	0;
    
    sensores.u32 =  GPIO_ReadValue(2);
	//sensor_pressao	= ADC_ChannelGetData( LPC_ADC, ADC_CHANNEL_2 );//*(5000/4096);
	//sensor_pressao  = sensor_pressao*6600/4096; // 3.3 *(12k/24k)
	// _DBD16 (sensor_pressao);
	valormedio	+=	ADC_ChannelGetData( LPC_ADC, ADC_CHANNEL_2 );
	if((++media)==(SAMPLE))
	{
		valormedio	/=	SAMPLE;
		sensor_pressao  = valormedio*6600/4096;
		media	=	0;
#ifdef	_DBGFWK
        	//_DBD16 (sensor_pressao);
        	//_DBG((void*)"\r");
#endif
	}
	//y = 0,0016x - 3,92		psi
	//sensor_pressao	=	(sensor_pressao*0.0016) - 3.92;
	// y = 0,0111x - 27,222		kPa
	//sensor_pressao	=	(sensor_pressao*0.0111) - 27,222;
}
